#-------------------------------------------------------------------------------
# Name:        News
# Purpose:
#
# Author:      Michael Blackwood
#
# Created:     07/12/2013
# Copyright:   (c) Monxcleyr Productions 2013
# Licence:     GPL v3
#-------------------------------------------------------------------------------
#!/usr/bin/env python

import urllib2, logging, io
from ..game import config

class News():

  """Download news from website"""

  def __init__(self):

    self.conf = config.Config()

    try:
      self.newsconfig = urllib2.urlopen('http://monxcleyr.tk/versions/news/news.ini')
      self.conf.readfp(io.BytesIO(self.newsconfig.read()))
      print self.newsconfig.read()
    except:
      logging.warning('Syncing to Monxcleyr News Service failed.')
      self.newsconfig = None


  def check(self, name):

    if self.newsconfig == None:
      return None

    # Get the news file
    try:
      newsfile = self.conf.get(name, 'latest')
      force = self.conf.get(name, 'force')
      force = force == 'True'
    except:
      return None


    # Try to load the linked news file
    try:
      newstext = urllib2.urlopen('http://monxcleyr.tk/versions/news/' + newsfile).read()
    except:
      logging.warning('Syncing to Monxcleyr Version Checking Service failed')
      return None

    if not force:

      try:
        f = open('resources/news/latest.txt', 'r')
        if str(f.read()) == str(newstext):
          f.close
          logging.info('Latest news already archived.')
          return None
        f.close
      except:
        pass

    f = open('resources/news/latest.txt', 'w')
    f.write(newstext)
    f.close
    try:
      f = open('resources/news/latest.txt', 'r+')
      f.write(newstext)
      f.close
    except:
      logging.warning('Failed to archive latest news')

    logging.info('Downloaded news from Monxcleyr Productions')
    return newstext

